package com.core.netty.http.Intercept;

import com.core.netty.http.work.HttpMyReponse;
import com.core.netty.http.work.HttpMyRequest;
import com.core.spring.DefaultMyApplication;
import com.core.spring.IocBeanFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyInterceptFactory {
    private static Map<String, MyIntercept> interceptMap = new ConcurrentHashMap<>();

    public static void init() {

        List<Class<?>> interceptClassList = ((DefaultMyApplication) IocBeanFactory.getInstant()).getInterceptClassList();

        for (Class<?> clazz : interceptClassList) {
            Object o = null;
            try {
                o = clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (o instanceof MyIntercept) {
                if (clazz.isAnnotationPresent(Intercept.class)) {
                    Intercept url = clazz.getAnnotation(Intercept.class);
                    interceptMap.put(url.value(), (MyIntercept) o);
                }
            }
        }
    }

    public static void addClass(Class<?> clazz) {
        Object o = null;
        try {
            o = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        if (o instanceof MyIntercept) {
            if (clazz.isAnnotationPresent(Intercept.class)) {
                Intercept url = clazz.getAnnotation(Intercept.class);
                interceptMap.put(url.value(), (MyIntercept) o);
            }
        }

    }

    public static void doIntercept(String url, HttpMyRequest request, HttpMyReponse reponse) {
        MyIntercept intercept = getIntercept(url);
        if (intercept != null) {
            intercept.doFilter(request, reponse);
        }

    }

    public static MyIntercept getIntercept(String url) {
        MyIntercept myInter = null;
        if (interceptMap.get(url) != null) {
            myInter = (MyIntercept) interceptMap.get(url);
        } else {
            for (Map.Entry<String, MyIntercept> entry : interceptMap.entrySet()) {
                String key = entry.getKey();
                if (key.contains("*")) {
                    if (key.endsWith("*") && url.contains(key.substring(0, key.indexOf("*")))) {
                        myInter = (MyIntercept) entry.getValue();
                    }
                }

            }
        }
        return myInter;
    }


}
